<route lang="json5">
{
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '登录',
    navigationBarBackgroundColor: '#cccccc',
  },
}
</route>

<template>
  <navbar text="登录" />
  <view class="scroll">
    <view class="public-page" :style="{ height: `calc(100vh - ${safeAreaInsets?.top}px - 44px)` }">
      <view class="public-background public-mt">
        <view class="public-height"></view>
        <view class="login-content">
          <view class="logo">
            <uv-image src="/static/logo.svg" mode="widthFix" width="100px">
              <template v-slot:loading>
                <uv-loading-icon mode="spinner"></uv-loading-icon>
              </template>
            </uv-image>
          </view>
          <view class="content">
            <view class="login-button">
              <uv-button
                size="large"
                form-type="submit"
                :open-type="checkboxValue[0] ? 'getPhoneNumber' : ''"
                @tap="beforeGetPhoneNumber"
                @getphonenumber="getPhoneNumber"
                shape="circle"
                type="primary"
                text="手机号快捷登录"
              ></uv-button>
            </view>
            <view class="agree">
              <uv-checkbox-group
                shape="circle"
                size="18"
                v-model="checkboxValue"
                placement="row"
                activeColor="#e50038"
              >
                <uv-checkbox :name="true" />
              </uv-checkbox-group>
              <view>
                <text>若手机号未注册将进入注册流程，注册即为同意</text>
                <uv-text
                  type="primary"
                  size="24rpx"
                  customStyle="display:inline"
                  @click="registration"
                  text="《心康用户注册协议》"
                ></uv-text>
                <uv-text
                  type="primary"
                  size="24rpx"
                  customStyle="display:inline"
                  @click="privacy"
                  text="《心康隐私协议》"
                ></uv-text>
                <uv-text
                  type="primary"
                  size="24rpx"
                  customStyle="display:inline"
                  @click="userKnow"
                  text="《用户知情协议书》"
                ></uv-text>
              </view>
            </view>
          </view>
        </view>
        <view class="public-height"></view>
      </view>
    </view>
  </view>
</template>

<script lang="js" setup>
import navbar from '@/components/navbar'
import { setUser, setSn, getSn } from '@/utils/publicMethods'
import {
  jscode_session,
  getuserphonenumber,
  token,
  login,
  getDevices,
} from '@/service/index/default'
const wx = {
  appId: import.meta.env.VITE_WX_APPID,
}
const { safeAreaInsets } = uni.getWindowInfo()
const isLogin = ref(false)
const getPhoneNumber = (e) => {
  isLogin.value = false
  if (e.errMsg !== 'getPhoneNumber:ok') return false
  uni.showLoading({ title: '正在登录' })
  // 1、调用登录弹窗，返回code，换取openid、session_key
  uni.login({
    success: async (res) => {
      if (!res?.code) {
        console.log('获取code失败1：', res.errno)
        uni.hideLoading()
        return
      }
      // 2、用code 换取openid
      const openid = await jscode_session_(res?.code)
      if (!openid) {
        uni.hideLoading()
        return
      }
      // 3、直接获取 token
      const access_token = await token_()
      if (!access_token) {
        uni.hideLoading()
        return
      }
      // 4、使用token, code, openid 换取手机号
      const phoneNumber = await getuserphonenumber_(e.code, openid, access_token)
      if (!phoneNumber) {
        uni.hideLoading()
        return
      }
      // 5、存储登录数据
      const result = await login_({
        phoneNumber,
        isAdmin: false,
        avatar: '',
        name: '',
        openId: openid,
      })
      uni.hideLoading()
      if (!result) return
      isLogin.value = true
      uni.$emit('loginEvent', true)
      uni.navigateBack()
    },
    fail: (err) => {
      uni.hideLoading()
      console.log('获取code失败2：', err.errMsg)
    },
  })
}

// 服务端接口 - 获取openid
const jscode_session_ = async (js_code) => {
  const { data, code, error } = await jscode_session({
    js_code,
    appid: wx.appId,
    grant_type: 'authorization_code',
  })
  if (code !== 200) {
    console.log('获取openid失败1：', error)
    return false
  }
  if (data?.errcode) {
    console.log('获取openid失败2：', data.errcode)
    return false
  }
  return data.openid
}

// 获取token
const token_ = async () => {
  const { data, code, error } = await token({
    appid: wx.appId,
    grant_type: 'client_credential',
  })
  if (code !== 200) {
    console.log('获取token失败1：', error)
    return false
  }
  if (data?.errcode) {
    console.log('获取token失败2：', data.errcode)
    return false
  }
  return data.access_token
}

// 获取phoneNumber
const getuserphonenumber_ = async (code_, openid, access_token) => {
  const { data, code, error } = await getuserphonenumber({
    access_token,
    openid,
    code: code_,
  })
  if (code !== 200) {
    console.log('获取phoneNumber失败1：', error)
    return false
  }
  if (data?.errcode) {
    console.log('获取phoneNumber失败2：', data.errcode)
    return false
  }
  return data.phone_info.phoneNumber
}

// 登录存储
const login_ = async (params) => {
  const { code, data, error } = await login(params)
  // && '400536ECB36926E1D0CC11C6151A0C50' 李目星
  //  && '00DCE47EE6DAFC9701DE17E193CED6C6' 是道
  //  && '8126C6771AC0C499BA6BA9868C0816DB' 张
  const userId = data.userId
  if (code !== 200) {
    uni.showToast({
      title: error,
      icon: 'none',
    })
    return false
  }

  setUser({
    phoneNumber: params.phoneNumber,
    isAdmin: data.isAdmin,
    userId: userId,
    avatar: data.avatar,
    name: data.name,
    loginTime: new Date().getTime().toString(),
  })
  const { code: code2, data: data2, error: error2 } = await getDevices({ userId: userId })
  if (code2 !== 200) {
    uni.showToast({
      title: `${error2}`,
      icon: 'none',
    })
    setSn('')
    return false
  }
  setSn(data2?.length ? data2[0].sn : '')
  return true
}

// 勾选协议
const checkboxValue = ref([false])
const beforeGetPhoneNumber = () => {
  if (!checkboxValue.value[0]) {
    uni.showToast({
      title: '请勾选隐私协议',
      icon: 'none',
    })
    return
  }
}

onShow(() => {
  isLogin.value = false
})
onUnload(() => {
  const pages = getCurrentPages() //当前页面栈
  if (pages.length > 1) {
    const beforePage = pages[pages.length - 2] //获取上一个页面实例对象
    beforePage.data.refreshIfNeeded = isLogin.value
  } else {
    uni.switchTab({ url: '/pages/home/index' })
  }
})

// 注册协议
const registration = () => {
  uni.navigateTo({ url: '/pages-sub/agreement/registration' })
}
// 稳私协议
const privacy = () => {
  uni.navigateTo({ url: '/pages-sub/agreement/privacy' })
}

// 用户知情协议
const userKnow = () => {
  uni.navigateTo({ url: '/pages-sub/agreement/userKnow' })
}

// const pages = getCurrentPages()
// const home = '/pages/home/index'
// const url =
//   pages.length < 1
//     ? home
//     : pages[1]?.options?.redirect
//       ? decodeURIComponent(pages[1].options.redirect)
//       : home

// // 跳转处理
// const jumpObject = {
//   url: url,
//   success: () => {
//     uni.showToast({
//       title: '登录成功',
//       icon: 'none',
//     })
//   },
//   fail: (err) => {
//     uni.showToast({
//       title: `登录失败${err.errMsg}`,
//       icon: 'none',
//     })
//   },
// }
// const isTabBar = tabBar.list.some((o) => url.includes(o.pagePath))

// if (isTabBar) {
//   uni.switchTab(jumpObject)
// } else {
//   uni.navigateTo(jumpObject)
// }

// 分享至好友/群聊
onShareAppMessage((res) => {
  return {
    title: '登录',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
// 分享到朋友圈
onShareTimeline((res) => {
  return {
    title: '登录',
    path: getCurrentPages()[0].$page.fullPath,
    success: (res) => {},
    fail: (res) => {},
  }
})
</script>

<style lang="scss" scoped>
.login-content {
  height: -webkit-fill-available;
  padding: 40rpx;
  background: #ffffff;
  border-radius: 20rpx;
  .logo {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 80%;
    :deep(.uv-image) {
      margin-bottom: 200rpx;
    }
  }
  .agree {
    display: flex;
    align-items: center;
    justify-content: center;
    margin-top: 46rpx;
    font-family:
      PingFangSC,
      PingFang SC;
    font-size: 24rpx;
    font-style: normal;
    line-height: 33rpx;
    color: #666666;
    text-align: left;
    :deep(.uv-text) {
      display: inline;
      flex: none;
    }
    :deep(.uv-checkbox-group) {
      display: inline;
      flex: none;
    }
  }
  .login-button {
    width: 100%;
    margin: auto;
    :deep(.uv-button__text) {
      font-size: 34rpx !important;
    }
  }
}
</style>
